import cv2
import numpy as np
import glob
import os

roi_dir = './roi'
files   = sorted(glob.glob(os.path.join(roi_dir, '*.*')))
ZOOM    = 20
ROI     = 21
BLACK_TH = 60        # 灰度低于此算黑

# 5 个区域坐标（左上、右上、左下、右下、中心）
ZONES = {
    'UL': (0, 0, 10, 10),   # x0,y0,x1,y1  不含右下边界
    'UR': (11, 0, 21, 10),
    'LL': (0, 11, 10, 21),
    'LR': (11, 11, 21, 21),
    'CT': (5, 5, 16, 16)    # 中心 11×11
}

def which_zone(gray, white_th=200, white_ratio_th=0.6):

    h, w = gray.shape
    total_white = (gray > white_th).sum() / (h*w)

    # 1. 大白场景
    if total_white > white_ratio_th:
        return 'WHITE',           # ← 你想给的固定角度

    # 2. 原逻辑：中心 + 四角
    ZONES = {
        'UL': (0, 0, 10, 10),
        'UR': (11, 0, 21, 10),
        'LL': (0, 11, 10, 21),
        'LR': (11, 11, 21, 21),
        'CT': (5, 5, 16, 16)
    }
    zone_ratio = {}
    for name, (x0, y0, x1, y1) in ZONES.items():
        patch = gray[y0:y1, x0:x1]
        ratio = (patch < 80).sum() / patch.size
        zone_ratio[name] = ratio

    center_ratio = zone_ratio.pop('CT')
    if center_ratio > 0.15:
        return 'CT', 0.0

    name = max(zone_ratio, key=zone_ratio.get)
    if zone_ratio[name] < 0.10:
        return 'NONE', 0.0

    angle_map = {'UL': -45, 'UR': -22.5, 'LL': 45, 'LR': 22.5}
    return name, angle_map[name]

for f in files:
    gray = cv2.imread(f, 0)
    zone, angle = which_zone(gray)

    # 放大画板
    show = cv2.resize(gray, (ROI*ZOOM, ROI*ZOOM), interpolation=cv2.INTER_NEAREST)
    show = cv2.cvtColor(show, cv2.COLOR_GRAY2BGR)

    # 画 5 个区域轮廓
    colors = {'UL': (0, 255, 255), 'UR': (0, 255, 0),
              'LL': (255, 0, 0),   'LR': (0, 0, 255), 'CT': (255, 255, 0)}
    for name, (x0, y0, x1, y1) in ZONES.items():
        cv2.rectangle(show, (x0*ZOOM, y0*ZOOM), (x1*ZOOM-1, y1*ZOOM-1),
                      colors[name], 2)

    # 文字
    info = f'zone={zone}  angle={angle:6.1f}°'
    cv2.putText(show, info, (10, ROI*ZOOM-10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)

    cv2.imshow('zones_20x', show)
    print(f'{os.path.basename(f)}  → {info}')
    cv2.waitKey(0)

cv2.destroyAllWindows()